<!--
- File:    添加文章.
-->
<template>
  <div>
    <div class="Web_Box">
      <div class="bg_fff minheight" style="padding-bottom: 10px">
        <div class="add_time2 f-cb">
          <input type="text" cl ass="g_ipts" placeholder="请输入文章标题" v-model="title">
        </div>
        <div>
          <div class="s_title" style="border-top: 1px #eee solid; border-bottom: none"><span style="margin-left: 0.5rem">类型</span></div>
          <div class="screen_b">
            <ul class="f-cb">
              <li v-for="tag in articleTagList" :class="{'tag-on': tagIsSelected(tag.d_id)}" @click="switchSelectTag(tag.d_id)">{{tag.d_name}}</li>
            </ul>
          </div>
        </div>
        <div class="add_block" @click="showSheet(-1)"><i class="iconfont icon-tianjia3"></i><span>点击添加文字、图片</span></div>
        <div v-for="(block, index) in content">
          <div class="srticle" v-if="block.type == 'text'">
            <textarea placeholder="点击输入文字..." v-model="block.value"></textarea>
          </div>
          <div class="srticle" v-if="block.type == 'img'">
            <div class="srtimg">
              <img :src="$config.imgsite + $config.uploadImgSrc + block.value + '_w640h320'">
              <div class="editimg">
                <ul class="f-cb">
                  <li><i class=" iconfont icon-bianji" @click="updateImg(index)"></i></li>
                  <li><i class=" iconfont icon-del3" @click="delImg(index)"></i></li>
                </ul>
              </div>
            </div>
          </div>
          <div class="add_block" @click="showSheet(index)"><i class="iconfont icon-tianjia3"></i><span>点击添加文字、图片</span></div>
        </div>
        <div id="select-pic">
          <input type="file" id="fileInput1" accept="image/jpeg,image/jpg,image/png,image/gif" style="display: none" @change="fileSelected">
        </div>
      </div>
    </div>
    <div class="artic_btn f-cb">
      <a class=" bg_a8a8a8" @click="back">取消</a><a class="bg_3dbb6e" @click="addArticle">发布</a>
    </div>
    <mt-actionsheet
      :actions="actions"
      v-model="sheetVisible">
    </mt-actionsheet>
  </div>
</template>

<script>
  import {Actionsheet} from 'mint-ui'
  import * as request from '../../../request'

  export default{
    data() {
      return {
        sheetVisible: false,
        title: '',
        articleTagList: [],
        tagSelectedList: [],
        content: [],
        editIndex: -1,
        actions: [{
          name: '添加文字',
          method: this.addTextBlock
        }, {
          name: '添加图片',
          method: this.getImg
        }],
        imgAction: 'add', // 用于判断是编辑图片还是删除图片
        sheetVisible2: false
      }
    },
    components: {
      'mt-actionsheet': Actionsheet
    },
    beforeRouteEnter (to, from, next) {
      request.getArticleClassify().then(data => {
        next(vm => {
          vm.articleTagList = data
        })
      }).catch(e => {
        next()
      })
    },
    beforeRouteLeave  (to, from, next) {
      this.$indicator.close()
      next()
    },
    created() {
      // this.$native.weixinShare(window.location.href)
    },
    mounted() {
      this.$native.weixinShare(window.location.href, '遇花园', null, '')
    },
    methods: {
      back() {
        this.$router.go(-1)
      },
      showSheet(index) {
        this.imgAction = 'add'
        this.editIndex = index
        this.sheetVisible = true
      },
      addTextBlock() {
        let block = {type: 'text', value: ''}
        this.content.splice(this.editIndex + 1, 0, block)
      },
      addImgBlock(url) {
        let block = {type: 'img', value: url}
        this.content.splice(this.editIndex + 1, 0, block)
      },
      switchSelectTag(tagId) {
        let index = this.tagSelectedList.indexOf(tagId)
        if (index == -1) {
          this.tagSelectedList.push(tagId)
        } else {
          this.tagSelectedList.splice(index, 1)
        }
      },
      tagIsSelected(tagId) {
        if (this.tagSelectedList.indexOf(tagId) != -1) {
          return true
        } else {
          return false
        }
      },
      addArticle() {
        if (this.title.trim() == '') {
          this.$toast('请输入标题')
          return
        }
        if (this.tagSelectedList.length <= 0) {
          this.$toast('请选择类型')
          return
        }
        for (let i = this.content.length - 1; i >= 0; i--) {
          if (this.content[i].type == 'text' && this.content[i].value == '') { // 删除内容为空的文本块
            this.content.splice(i, 1)
          }
        }
        if (this.content.length <= 0) {
          this.$toast('请添加文字或图片')
          return
        }
        this.$request.addArticle(this.tagSelectedList, this.title, this.content).then(data => {
          this.$toast('发布成功')
          this.$router.go(-1)
        }).catch(e => {
          this.$toast('发布失败:' + e.msg)
        })
      },
      updateImg(index) {
        this.editIndex = index
        this.imgAction = 'update'
        this.getImg()
      },
      getImg() {
        let deviceType = this.$utils.getDeviceType()
        if (deviceType == 'wx-iPhone' || deviceType == 'wx-Android') {
          wx.chooseImage({ // eslint-disable-line
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
              var localId = res.localIds[0]
              wx.getLocalImgData({ // eslint-disable-line
                localId: localId,
                success: (res) => {
                  var localData = res.localData
                  localData = localData.replace('jgp', 'jpeg')
                  if (localData.indexOf('data:image/jpeg;base64,') == -1) {
                    localData = 'data:image/jpeg;base64,' + localData
                  }
                  this.$indicator.open('上传图片中...')
                  this.$request.uploadImg(localData).then(data => {
                    if (this.imgAction == 'update') {
                      this.content[this.editIndex].value = data[0]
                    } else {
                      this.addImgBlock(data)
                    }
                  }).catch(e => {
                    this.$toast('上传图片失败:' + e.msg)
                  }).finally(() => {
                    this.$indicator.close()
                  })
                }
              })
            }
          })
        } else {
          this.getFromAlbum()
        }
      },
      delImg(index) {
        this.$messageBox.confirm('确定删除图片?').then(action => {
          this.content.splice(index, 1)
        }).catch(() => {
        })
      },
      getFromAlbum() {
        var imgInputFile = document.getElementById('fileInput1')
        if (imgInputFile.hasAttribute('capture')) {
          imgInputFile.removeAttribute('capture')
        }
        this.$utils.clickFileInput(imgInputFile)
      },
      clearInputFile() {
        var self = this
        var selectPic = document.getElementById('select-pic')
        var randomStr = Math.random().toString(36)
        selectPic.innerHTML = '<input id="fileInput1" type="file" title="" ' + randomStr + '"  accept="image/jpeg,image/jpg,image/png,image/gif"  id="fileInput1" style="visibility: hidden" >'
        document.getElementById('fileInput1').addEventListener('change', self.fileSelected)
      },
      fileSelected(e) {
        try {
          var reader = new window.FileReader()
          reader.onload = (e) => {
            if (e.total > 1024 * 1024 * 5) {
              this.$toast('图片大小不能超过5M')
              return
            }
            // 调用图片压缩方法
            // console.log("成功加载图片，开始压缩图片...")
            this.$utils.compress(e.target.result, (imgDataUrl) => {
              // todo 调用上传图片接口
              this.$request.uploadImg(imgDataUrl).then(data => {
                if (this.imgAction == 'update') {
                  this.content[this.editIndex].value = data[0]
                } else {
                  this.addImgBlock(data)
                }
              }).catch(e => {
                this.$toast('上传图片失败:' + e.msg)
              })
            })
          }
          // 选取同名文件不会再次触发change事件，所以在加载后替换input控件
          reader.onloadend = (e) => {
            this.clearInputFile()
          }
          reader.readAsDataURL(e.target.files[0])
        } catch (e) {
          console.log('读取图片文件发生了错误')
          console.log(e)
        }
      }
    }
  }
</script>

<style>
  .tag-on {
    background-color: #3dbb6e !important;
    color: #fff !important;
  }
</style>
